<template>
  <div class="comment-management-container">
    <!-- Header with title and action buttons -->
    <div class="header-container">
      <h2 class="page-title">评论管理</h2>
      <div class="btn-group">
        <el-button-group>
          <el-button type="danger" :icon="Delete" @click="deleteAll"
            >删除所选</el-button
          >
        </el-button-group>
      </div>
    </div>

    <!-- Search filters -->
    <div class="filter-container">
      <el-input
        v-model="search.content"
        placeholder="搜索评论内容"
        prefix-icon="Search"
        clearable
        @change="onSearchChange"
      />
      <el-select
        v-model="search.commentLevel"
        placeholder="评论级别"
        clearable
        @change="onSearchChange"
      >
        <el-option
          v-for="(value, key) in levelMap"
          :key="key"
          :label="value.text"
          :value="key"
        />
      </el-select>
      <el-date-picker
        v-model="dateRange"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        @change="onSearchChange"
      />
      <el-button type="primary" :icon="Search" @click="onSearchChange"
        >搜索</el-button
      >
    </div>

    <!-- Table with shadow and hover effect -->
    <el-card class="table-card" shadow="hover">
      <el-table
        ref="tableRef"
        @sort-change="sortChange"
        :data="tableData"
        style="width: 100%"
        border
        highlight-current-row
        :row-class-name="tableRowClassName"
        v-loading="loading"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column
          prop="activityTitle"
          label="评论活动名称"
          min-width="200"
          show-overflow-tooltip
        />
        <el-table-column
          sortable
          prop="content"
          label="评论内容"
          min-width="250"
          show-overflow-tooltip
        />
        <el-table-column sortable prop="likeCount" label="喜欢人数" width="120">
          <template #default="scope">
            <span class="like-count">
              <el-icon><Star /></el-icon> {{ scope.row.likeCount }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          sortable
          prop="commentLevel"
          label="评论级别"
          width="120"
        >
          <template #default="scope">
            <el-tag
              :type="levelMap[scope.row.commentLevel]?.type || 'info'"
              :effect="scope.row.commentLevel === 1 ? 'dark' : 'light'"
              class="level-tag"
            >
              {{ levelMap[scope.row.commentLevel]?.text || "未知状态" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          sortable
          prop="commentTime"
          label="评论时间"
          width="180"
        >
          <template #default="scope">
            <span class="time-text">
              <el-icon><Calendar /></el-icon> {{ scope.row.commentTime }}
            </span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="160">
          <template #default="scope">
            <div class="action-buttons">
              <el-button
                type="primary"
                size="small"
                :icon="Edit"
                @click="handleCommentEdit(scope.row)"
              >
                编辑
              </el-button>
              <el-popconfirm
                title="确定删除此评论吗？"
                @confirm="handleCommentDelete(scope.row.id)"
              >
                <template #reference>
                  <el-button type="danger" size="small" :icon="Delete">
                    删除
                  </el-button>
                </template>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- Pagination with better alignment -->
    <div class="pagination-container">
      <el-pagination
        background
        :page-sizes="[10, 20, 30, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        :current-page="pagination.page"
        :page-size="pagination.size"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- Edit Dialog with improved UI -->
    <el-dialog
      v-model="commentEditDialog.isVisible"
      :title="commentEditDialog.title"
      width="550px"
      align-center
      destroy-on-close
    >
      <el-form
        label-width="100px"
        label-position="left"
        :model="commentDetail"
        ref="commentForm"
      >
        <el-form-item label="活动名称" prop="activityTitle">
          <el-input v-model="commentDetail.activityTitle" disabled />
        </el-form-item>
        <el-form-item label="评论内容" prop="content">
          <el-input
            v-model="commentDetail.content"
            type="textarea"
            :rows="4"
            placeholder="请输入评论内容"
          />
        </el-form-item>
        <el-form-item label="评论级别" prop="commentLevel">
          <el-radio-group v-model="commentDetail.commentLevel">
            <el-radio :label="1">
              <el-tag type="success" effect="dark" class="radio-tag"
                >好评</el-tag
              >
            </el-radio>
            <el-radio :label="2">
              <el-tag type="primary" effect="light" class="radio-tag"
                >中评</el-tag
              >
            </el-radio>
            <el-radio :label="3">
              <el-tag type="danger" effect="light" class="radio-tag"
                >差评</el-tag
              >
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="commentEditDialog.isVisible = false"
            >取消</el-button
          >
          <el-button type="primary" @click="saveEdit">保存</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- Add Dialog -->
    <el-dialog
      v-model="plusAndEditDialog.isVisible"
      :title="plusAndEditDialog.title"
      width="550px"
      align-center
      destroy-on-close
    >
      <el-form
        label-width="100px"
        label-position="left"
        :model="addCommentDetail"
        ref="addCommentForm"
      >
        <el-form-item label="活动名称" prop="activityTitle" required>
          <el-input
            v-model="addCommentDetail.activityTitle"
            placeholder="请输入活动名称"
          />
        </el-form-item>
        <el-form-item label="评论内容" prop="content" required>
          <el-input
            v-model="addCommentDetail.content"
            type="textarea"
            :rows="4"
            placeholder="请输入评论内容"
          />
        </el-form-item>
        <el-form-item label="评论级别" prop="commentLevel" required>
          <el-radio-group v-model="addCommentDetail.commentLevel">
            <el-radio :label="1">
              <el-tag type="success" effect="dark" class="radio-tag"
                >好评</el-tag
              >
            </el-radio>
            <el-radio :label="2">
              <el-tag type="primary" effect="light" class="radio-tag"
                >中评</el-tag
              >
            </el-radio>
            <el-radio :label="3">
              <el-tag type="danger" effect="light" class="radio-tag"
                >差评</el-tag
              >
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="plusAndEditDialog.isVisible = false"
            >取消</el-button
          >
          <el-button type="primary" @click="saveAdd">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  commentPage,
  commentDeleteByUserId,
  commentDeleteBatch,
  commentAdd,
  commentEdit,
} from "@/apis/user/comment";
import { reactive, onMounted, ref, computed } from "vue";
import { useRouter } from "vue-router";
import { getFormatTime } from "@/apis/utility";
import {
  Delete,
  Edit,
  Plus,
  Search,
  Star,
  Calendar,
} from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";

const router = useRouter();

// 数据
const tableData = ref([]);
const loading = ref(false);

// 分页
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0,
});

// 搜索输入框搜索条件
const search = reactive({
  content: "",
  commentLevel: "",
  commentTime: null,
});

// 过滤对应的条件
const filter = computed(() => {
  const result = {};
  if (search.content) {
    result.content = search.content;
  }
  if (search.commentLevel) {
    result.commentLevel = search.commentLevel;
  }
  if (search.commentTime && search.commentTime.length === 2) {
    result.startTime = search.commentTime[0];
    result.endTime = search.commentTime[1];
  }
  return result;
});

// 存储排序字段
const orders = reactive({
  column: "commentTime",
  isAsc: false,
});
// 近7天
const getLastSevenDays = () => {
  const end = new Date();
  const start = new Date();
  start.setTime(start.getTime() - 3600 * 1000 * 24 * 6); // 减去6天，加上今天，共7天
  return [start.toISOString().split("T")[0], end.toISOString().split("T")[0]];
};
const dateRange = ref(getLastSevenDays());

// 评论获取数据
const getComment = async () => {
  loading.value = true;
  if (dateRange.value && dateRange.value.length === 2) {
    filter.value.startTime = dateRange.value[0];
    filter.value.endTime = dateRange.value[1];
  } else {
    delete filter.value.startTime;
    delete filter.value.endTime;
  }

  try {
    const result = await commentPage(
      {
        filter: filter.value,
        search: search,
        orders: [orders],
      },
      pagination.page,
      pagination.size
    );
    tableData.value = result.data.records;
    pagination.total = result.data.total;
  } catch (error) {
    console.error(error);
    ElMessage.error("获取评论数据失败");
  } finally {
    loading.value = false;
  }
};

// 编辑评论提交函数
const editCommentEdit = async (row) => {
  loading.value = true;
  try {
    const result = await commentEdit(row);
    if (result !== undefined) {
      commentEditDialog.isVisible = false;
      ElMessage.success("评论编辑成功");
      await getComment();
    }
  } catch (error) {
    console.error(error);
    ElMessage.error("编辑评论失败");
  } finally {
    loading.value = false;
  }
};

// 添加评论提交函数
const addCommentAdd = async (row) => {
  loading.value = true;
  try {
    const result = await commentAdd(row);
    if (result !== undefined) {
      plusAndEditDialog.isVisible = false;
      ElMessage.success("评论添加成功");
      await getComment();
    }
  } catch (error) {
    console.error(error);
    ElMessage.error("添加评论失败");
  } finally {
    loading.value = false;
  }
};

// 根据ID删除评论提交函数
const deleteByIdCommentEdit = async (id) => {
  loading.value = true;
  try {
    const result = await commentDeleteByUserId(id);
    ElMessage.success("评论删除成功");
    await getComment();
  } catch (error) {
    console.error(error);
    ElMessage.error("删除评论失败");
  } finally {
    loading.value = false;
  }
};

// 批量删除评论提交函数
const deleteBatchCommentEdit = async (ids) => {
  loading.value = true;
  try {
    const result = await commentDeleteBatch(ids);
    ElMessage.success("批量删除评论成功");
    await getComment();
  } catch (error) {
    console.error(error);
    ElMessage.error("批量删除评论失败");
  } finally {
    loading.value = false;
  }
};

// 分页处理函数
const handleSizeChange = (size) => {
  pagination.size = size;
  getComment();
};

const handleCurrentChange = (page) => {
  pagination.page = page;
  getComment();
};

// 页面加载时执行
onMounted(async () => {
  await getComment();
});

// 编辑评论信息
const commentEditDialog = reactive({
  isVisible: false,
  title: "编辑用户评论",
});

// 编辑评论数据
const commentDetail = reactive({});

// 编辑评论触发函数
const handleCommentEdit = async (row) => {
  Object.assign(commentDetail, JSON.parse(JSON.stringify(row)));
  commentEditDialog.isVisible = true;
};

// 触发评论保存
const saveEdit = async () => {
  await editCommentEdit(commentDetail);
};

// 删除评论触发函数
const handleCommentDelete = async (id) => {
  await deleteByIdCommentEdit(id);
};

// 获取表格组件引用对象
const tableRef = ref();

// 搜索输入框对应的触发事件
const onSearchChange = async () => {
  pagination.page = 1; // 重置页码
  await getComment();
};

// 删除所有选中选中行
const deleteAll = async () => {
  const selectionRows = tableRef.value.getSelectionRows();
  if (selectionRows.length === 0) {
    ElMessage.warning("请至少选择一条记录");
    return;
  }

  ElMessageBox.confirm("确定要删除所选评论吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const ids = selectionRows.map((row) => row.id);
      await deleteBatchCommentEdit(ids);
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

/**
 * 表格排序函数
 */
const sortChange = ({ prop, order }) => {
  Object.assign(orders, {
    column: prop,
    isAsc: order === "ascending",
  });
  getComment();
};

// 添加评论数据
const addCommentDetail = reactive({
  commentLevel: 1,
});

/**
 * 添加对话框
 */
const plusAndEditDialog = reactive({
  isVisible: false,
  title: "添加新评论",
});

// 触发评论保存
const saveAdd = async () => {
  await addCommentAdd(addCommentDetail);
};

/**
 * 添加一行数据
 */
const plusRow = async () => {
  Object.keys(addCommentDetail).forEach((key) => {
    addCommentDetail[key] = key === "commentLevel" ? 1 : null;
  });
  plusAndEditDialog.isVisible = true;
};

// 评论级别
const levelMap = {
  1: { text: "好评", type: "success" },
  2: { text: "中评", type: "primary" },
  3: { text: "差评", type: "danger" },
};

// 表格行样式
const tableRowClassName = ({ row }) => {
  if (row.commentLevel === 3) {
    return "negative-row";
  }
  return "";
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return "";

  try {
    return getFormatTime(dateString, "YYYY-MM-DD HH:mm");
  } catch (error) {
    return dateString;
  }
};
</script>

<style lang="less" scoped>
.comment-management-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  margin: 0;
  font-size: 22px;
  color: #303133;
  font-weight: 600;
}

.filter-container {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
  flex-wrap: wrap;

  .el-input {
    max-width: 250px;
  }

  .el-select {
    width: 140px;
  }
}

.table-card {
  margin-bottom: 20px;
  border-radius: 8px;

  :deep(.el-card__body) {
    padding: 0;
  }
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.time-text,
.like-count {
  display: flex;
  align-items: center;
  gap: 5px;
}

.level-tag {
  min-width: 48px;
  text-align: center;
}

.radio-tag {
  margin-left: 5px;
}

:deep(.el-table .negative-row) {
  background-color: #fff0f0;
}

:deep(.el-table__row:hover) {
  background-color: #f0f7ff !important;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding-top: 20px;
}

// 响应式适配
@media screen and (max-width: 768px) {
  .filter-container {
    flex-direction: column;

    .el-input,
    .el-select,
    .el-date-picker {
      max-width: 100%;
      width: 100%;
    }
  }

  .header-container {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
}
</style>
